//
//  FeedBackVC.m
//  BXlive
//
//  Created by bxlive on 2017/5/8.
//  Copyright © 2017年 cat. All rights reserved.
//

#import "FeedBackVC.h"
#import "UITextView+Kit.h"
#import "SelectImageCell.h"
#import "FilePathHelper.h"
#import "BXSAMTextView.h"
#import "BXGradientButton.h"
#import <FDFullscreenPopGesture/UINavigationController+FDFullscreenPopGesture.h>
#import <SLDeveloperTools/SLDeveloperTools.h>
#import <Masonry/Masonry.h>

@interface FeedBackVC ()<UITextFieldDelegate,UITextViewDelegate,UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)UIView *navigationView;

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) BXSAMTextView *textView;
@property (nonatomic,strong) UITextField *numField;
@property (nonatomic,strong) SelectImageCell *mainImageCell;//
//要显示的cell数组
@property (nonatomic,strong) NSMutableArray *cellArrayM;
@property (nonatomic,strong) NSMutableArray *imageArrayM;
@end

@implementation FeedBackVC

- (NSMutableArray *)cellArrayM
{
    if (!_cellArrayM) {
        _cellArrayM = [NSMutableArray array];
    }
    return _cellArrayM;
}
- (NSMutableArray *)imageArrayM
{
    if (!_imageArrayM) {
        _imageArrayM = [NSMutableArray array];
    }
    return _imageArrayM;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.navigationItem.title = NSLocalizedString(@"意见反馈", nil);
    self.fd_prefersNavigationBarHidden = YES;
    [self.view setBackgroundColor:[UIColor sl_colorWithHex:0xFFFFFF]];
    [self setupNavigationView];
    
    [self createView];
    
}
-(void)setupNavigationView{
    _navigationView = [UIView new];
    [self.view addSubview:_navigationView];
    [_navigationView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.height.mas_equalTo(__kTopAddHeight+64);
    }];
    [_navigationView setBackgroundColor:[UIColor sl_colorWithHex:0xFFFFFF]];
    WS(weakSelf);
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn addTarget:self action:@selector(pop) forControlEvents:BtnTouchUpInside];
    [_navigationView addSubview:backBtn];
    [backBtn setImage:CImage(@"back_black") forState:BtnNormal];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.mas_equalTo(0);
        make.width.height.mas_equalTo(44);
    }];
    UILabel *label = [UILabel createLabelWithFrame:CGRectZero BackgroundColor:SLClearColor Text:NSLocalizedString(@"意见反馈", nil) Font:SLBFont(__ScaleWidth(18)) TextColor:sl_textColors];
    label.textAlignment = 1;
    [_navigationView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(44);
        make.right.mas_equalTo(-44);
        make.centerY.equalTo(weakSelf.navigationView.mas_bottom).offset(-22);
        make.height.mas_equalTo(25);
    }];
}



-(void)createView {
    WS(weakSelf);
    UIView *textSuperView = [UIView new];
    [self.view addSubview:textSuperView];
    [textSuperView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(__ScaleWidth(12));
        make.right.mas_equalTo(__ScaleWidth(-12));
        make.top.equalTo(weakSelf.navigationView.mas_bottom).offset(__ScaleWidth(15));
        make.height.mas_equalTo(__ScaleWidth(165));
    }];
    textSuperView.backgroundColor = sl_subBGColors;
    textSuperView.layer.masksToBounds = YES;
    textSuperView.layer.cornerRadius = 12.0f;
    
    
    NSAttributedString *attri = [[NSAttributedString alloc]initWithString:NSLocalizedString(@"请描述您遇到问题的功能名称，以及问题实现，也可以上传手机截图（非WIFI环境会消耗流量）", nil) attributes:@{NSForegroundColorAttributeName:MinorColor, NSFontAttributeName:CFont(14)}];
    _textView = [[BXSAMTextView alloc]init];
    _textView.backgroundColor = SLClearColor;
    _textView.delegate = self;
    _textView.font = [UIFont systemFontOfSize:14.f];
    _textView.textColor =sl_textColors;
    _textView.textAlignment = NSTextAlignmentLeft;
    _textView.editable = YES;
    _textView.layer.cornerRadius = 12.0f;
    _textView.attributedPlaceholder = attri;
    [textSuperView addSubview:_textView];
    
    [_textView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(__ScaleWidth(15));
        make.right.mas_equalTo(__ScaleWidth(-15));
        make.top.mas_equalTo(__ScaleWidth(15));
        make.bottom.mas_equalTo(__ScaleWidth(-15));
    }];
    
    UIView *numTFSuperV = [UIView new];
    [self.view addSubview: numTFSuperV];
    [numTFSuperV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(textSuperView);
        make.height.mas_equalTo(__ScaleWidth(50));
        make.top.equalTo(textSuperView.mas_bottom).offset(__ScaleWidth(10));
    }];
    numTFSuperV.layer.masksToBounds = YES;
    numTFSuperV.layer.cornerRadius = 12.0f;
    numTFSuperV.backgroundColor = sl_subBGColors;
    
    self.numField = [self addTextFieldWithRects:CGRectZero borderStyle:UITextBorderStyleNone isSecurity:NO placeholder:NSLocalizedString(@"您的手机号/邮箱 (必填)", nil) delegate:self];
    self.numField.layer.cornerRadius = 12.0f;
    self.numField.backgroundColor = sl_subBGColors;
    self.numField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:NSLocalizedString(@"您的手机号/邮箱 (必填)", nil) attributes:@{NSForegroundColorAttributeName:sl_textSubColors}];
    self.numField.leftViewMode = UITextFieldViewModeAlways;
    self.numField.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 6, 0)];
    self.numField.textColor =sl_textColors;
    [numTFSuperV addSubview:self.numField];
    UIButton *clearBtn =[self.numField valueForKey:@"_clearButton"];
    [clearBtn setImage:CImage(@"login_clear") forState:BtnNormal];
    [self.numField mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(__ScaleWidth(15));
        make.right.mas_equalTo(__ScaleWidth(-15));
        make.height.mas_equalTo(__ScaleWidth(20));
        make.centerY.mas_equalTo(__ScaleWidth(0));
    }];
    
//    self.numField.sd_layout.leftSpaceToView(self.view,20).topSpaceToView(self.tableView,20).rightSpaceToView(self.view,20).heightIs(35);
    
    self.tableView = [[UITableView alloc] init];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = 0;
    self.tableView.layer.cornerRadius = 4.0f;
    self.tableView.backgroundColor = SLClearColor;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(__ScaleWidth(146));
        make.top.equalTo(numTFSuperV.mas_bottom).offset(__ScaleWidth(15));
    }];
//    self.tableView.sd_layout.leftSpaceToView(self.view, 20).rightSpaceToView(self.view, 20).topSpaceToView(self.textView, 20).heightIs(110);
    
    self.mainImageCell = [[SelectImageCell alloc] init];
    self.mainImageCell.titleLabel.text = NSLocalizedString(@"图片", nil);
    self.mainImageCell.maxImageNumber = 1;
    self.mainImageCell.isCanEdit = YES;
    self.mainImageCell.backgroundColor = [UIColor clearColor];

    [self.mainImageCell returnSelectImages:^(NSMutableArray *imagesArr) {
        self.imageArrayM = imagesArr;
    }];

    [self.cellArrayM addObjectsFromArray:@[_mainImageCell]];
    
    
    UIButton *useBt = [self creatButtonWithRect:CGRectZero backgroundColor: sl_normalColors backgroundImageName:nil title:NSLocalizedString(@"提交", nil) target:self action:@selector(submit) cornerReadio:0.0 isShadow:NO];
    [self.view addSubview:useBt];
    
    [useBt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.textView);
        make.height.mas_equalTo(__ScaleWidth(44));
        make.top.equalTo(weakSelf.tableView.mas_bottom).offset(__ScaleWidth(45));
    }];
    
//    useBt.sd_layout.leftSpaceToView(self.view,20).rightSpaceToView(self.view,20).heightIs(40).topSpaceToView(self.numField,30);
//    useBt.sd_cornerRadius = @(20);
    useBt.layer.masksToBounds = YES;
    useBt.layer.cornerRadius = __ScaleWidth(22);
    useBt.titleLabel.font = SLBFont(16);
}

-(void)submit{
    if (self.textView.text.length<=0) {
        [BGProgressHUD showInfoWithMessage:NSLocalizedString(@"请输入你想要反馈的内容", nil)];
        return;
    }else if (self.numField.text.length<=0) {
        [BGProgressHUD showInfoWithMessage:NSLocalizedString(@"请输入联系方式", nil)];
        return;
    } else{
       if (self.imageArrayM.count>0) {
           UIImage * image = self.imageArrayM[0];
           NSData *data = UIImageJPEGRepresentation(image, .8);
           NSString *filePath = [self getImageFilePath:data];
           [BGProgressHUD showLoadingWithMessage:nil];
           [SLUpLoadAndDownloadTools uploadFileWithType:@"images" filePath:filePath success:^(NSDictionary *jsonDic, BOOL flag, NSMutableArray *models) {
               if (flag) {
                   [[NewHttpRequestPort sharedNewHttpRequestPort] FeedbackViewBack:@{@"cover_url":jsonDic[@"filePath"],@"contact":self.numField.text,@"content":self.textView.text} Success:^(id responseObject) {
                       if([responseObject[@"code"] integerValue] == 0){
                           [self.navigationController popViewControllerAnimated:YES];
                       }
                       [BGProgressHUD showInfoWithMessage:responseObject[@"msg"]];
                   } Failure:^(NSError *error) {
                       [BGProgressHUD hidden];
                   }];
               } else {
                   [BGProgressHUD showInfoWithMessage:NSLocalizedString(@"上传失败", nil)];
               }
           } failure:^(NSError *error) {
               [BGProgressHUD showInfoWithMessage:NSLocalizedString(@"上传失败", nil)];
           }];
       } else {
           [[NewHttpRequestPort sharedNewHttpRequestPort] FeedbackViewBack:@{@"cover_url":@"",@"contact":self.numField.text,@"content":self.textView.text} Success:^(id responseObject) {
               if([responseObject[@"code"] integerValue] == 0){
                   [self.navigationController popViewControllerAnimated:YES];
               }
              [BGProgressHUD showInfoWithMessage:responseObject[@"msg"]];
               
           } Failure:^(NSError *error) {
               [BGProgressHUD hidden];
           }];
       }
    }
}
-(NSString *)getImageFilePath:(NSData *)imageData {
    NSString *path = [[FilePathHelper getDocumentsPath] stringByAppendingPathComponent:@"temp.jpg"];
    if([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
    }
    [imageData writeToFile:path atomically:YES];
    return path;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.cellArrayM.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.cellArrayM[indexPath.row];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return __ScaleWidth(146);
}
-(UITextField *)addTextFieldWithRects:(CGRect)rect borderStyle:(UITextBorderStyle)borderStyle isSecurity:(BOOL)isSecurity  placeholder:(NSString *)placeholder delegate:(id)delegate{
    
    UITextField *textfiled = [[UITextField alloc]initWithFrame:rect];
//    textfiled.placeholder = placeholder;
    textfiled.delegate = delegate;
    textfiled.borderStyle = borderStyle;
    textfiled.secureTextEntry = isSecurity;
    textfiled.font = SLPFFont(13);
    textfiled.backgroundColor = SLClearColor;
    textfiled.autocapitalizationType = UITextAutocapitalizationTypeNone;
    textfiled.contentVerticalAlignment =UIControlContentVerticalAlignmentCenter;
    textfiled.contentHorizontalAlignment  = UIControlContentHorizontalAlignmentCenter;
    textfiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    textfiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholder attributes:@{NSFontAttributeName:SLPFFont(13)}];
//    [textfiled setValue:CFont(13) forKeyPath:@"_placeholderLabel.font"];
    
    return textfiled;
}
-(UIButton *)creatButtonWithRect:(CGRect)rect
                 backgroundColor:(UIColor *)bgColor
             backgroundImageName:(NSString *)imageName
                           title:(NSString *)title
                          target:(id)target
                          action:(SEL)action
                    cornerReadio:(CGFloat)cornerReadio
                        isShadow:(BOOL)isShadow
{
    UIButton * button = [[BXGradientButton alloc]init];
    button.frame = rect;
    [button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [button setTitle:title forState:UIControlStateNormal];
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    button.layer.cornerRadius = cornerReadio;
    
    if (isShadow == YES) {
        button.layer.shadowColor = [UIColor grayColor].CGColor;
        button.layer.shadowOffset = CGSizeMake(2, 2);
        button.layer.shadowOpacity = 5.0;
        button.layer.shadowRadius = 5.0;
    }
    return button;
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.view endEditing:YES];
    
}
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
